<template>
	<view @longtap.stop="longtap">
		<canvas :width="destWidth" :height="destHeight" :canvas-id="item.id" :id="item.id" :style="{width:width,height: height}" v-for="item in listCode" :key="item.id" @error="handleError">
		</canvas>
	</view>
</template>

<script>
	import { defineComponent, reactive, toRefs, watch, onMounted, nextTick, getCurrentInstance, ref } from 'vue';
	import { BarCode, GetCodeImg, GetPixelRatio, GetPx } from './hello.js';
	import { getUUid, deepClone, platform } from './helper.js'
	export default defineComponent({
		name: 'WBarcode',
		props: {
			options: {
				type: Object,
				required: true,
				default: () => {
					return {

					}
				}
			}
		},
		setup(props, ctx) {
			const opt = props.options;
			const that = getCurrentInstance();
			let info = reactive({
				id: getUUid(),
				destWidth: GetPixelRatio() * GetPx(opt.width) + 'px',
				destHeight: GetPixelRatio() * GetPx(opt.height) + 'px',
				width: GetPx(opt.width) + 'px',
				height: GetPx(opt.height) + 'px',
				listCode: []
			})
			let canvasImg = ref('')
			onMounted(() => {
				SpecialTreatment(opt);
				nextTick(() => {
					generateCode(opt)
				})
			});
			watch(() => props.options, (val) => {
				SpecialTreatment(val)
				info.destWidth = GetPixelRatio() * GetPx(val.width) + 'px',
					info.destHeight = GetPixelRatio() * GetPx(val.height) + 'px',
					info.width = GetPx(val.width) + 'px',
					info.height = GetPx(val.height) + 'px',
					setTimeout(() => {
						generateCode(val)
					}, 50)
			}, { deep: true })
			const generateCode = (val) => {
				try {
					const parameter = { ...val, source: platform(), id: info.id, ctx: that };
					BarCode(parameter, (res) => {
						ctx.emit('generate', res)
					})
				} catch (err) {
					// console.warn(err)
				}
			}
			const GetImg = async () => {
				try {
					return await GetCodeImg({ id: info.id, width: opt.width, height: opt.height, ctx: ctx });
				} catch (e) {
					// console.warn(e)
				}
			};
			const SpecialTreatment = (val) => { //微信小程序渲染多个canvas特殊处理
				let obj = deepClone(val);
				obj.id = info.id;
				info.listCode = [obj];
			};
			// 长按事件
			const longtap = (e) => {
				ctx.emit('press', e)
			}
			// canvas创建错误 触发
			const handleError = (e) => {
				ctx.emit('error', e.detail)
			}
			return {
				...toRefs(info),
				handleError,
				longtap
			};
		}
	});
</script>